#include "ResMgr.h"
#include "..\\tinyXML\\tinyxml.h"

TResourceImageList ResourceManager::mapLoadedResources;
TResourceAnimInfoList ResourceManager::mapLoadedAnimation;

bool ResourceManager::LoadResourceList(string filename)
{    
    TiXmlDocument  doc;    
    doc.LoadFile(filename.c_str());    
    TiXmlElement* root = doc.RootElement();
    TiXmlElement *level1 = root->FirstChildElement();

    string strBitmap = string("Bitmap");
    string strAnimation = string("Animation");    
    do
    {       
        string Value = string(level1->Value());
        if (Value == strBitmap)
        {
            const char *name  = level1->Attribute("Name");
            const char *value = level1->GetText();
            mapLoadedResources[string(name)] = new TGDKImage((char*)value);
        }else if (Value == strAnimation){
            const char *name  = level1->Attribute("Name");
            string filename = "";
            AnimInfo *info = new AnimInfo();            
            TiXmlElement *level2 = level1->FirstChildElement();
            do 
            {
                string Value = string(level2->Value());
                string content = level2->GetText();
                if (Value == string("File"))
                {
                    filename = content;
                }else if (Value == string("Rows")){
                    info->rows = atoi(content.c_str());
                }else if (Value == string("Cols")){
                    info->cols = atoi(content.c_str());
                }else if (Value == string("Delay")){
                    info->delay = atoi(content.c_str());
                }
                if (level2 == level1->LastChild()) break;
                level2 = level2->NextSiblingElement();                
            } while (true);            
            info->img = new TGDKImage((char *)filename.c_str());
            mapLoadedAnimation[string(name)] = info;
        }
        if (level1 == root->LastChild()) break;
        level1 = level1->NextSiblingElement();                
    }while (true);
    return true;
}

void ResourceManager::FreeResources()
{
    TResourceImageList::iterator it = mapLoadedResources.begin();
    for(;it != mapLoadedResources.end();it++)
    {
        delete (*it).second;
    }
    mapLoadedResources.clear();
}

TGDKImage* ResourceManager::GetResource(string name)
{
    return mapLoadedResources[name];
}

TGDKSprite* ResourceManager::CreateAnimation(string name, int x, int y )
{
    AnimInfo *info = mapLoadedAnimation[name];
    if (!info) return NULL;
    return new TGDKSprite(*info->img, NULL, x, y, info->rows, info->cols, info->delay );
}


